package cn.itsource.org.service.impl;

import cn.itsource.common.util.AjaxResult;
import cn.itsource.org.domain.Menu;
import cn.itsource.org.domain.Role;
import cn.itsource.org.mapper.RoleMapper;
import cn.itsource.org.ro.RoleRo;
import cn.itsource.org.service.IRoleService;
import cn.itsource.common.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 业务实现类：
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Override
    @Transactional
    public void update(RoleRo role) {
        //删除对应的菜单和权限关联表
        roleMapper.deleteRoleMenuByRoleId(role.getId());
        roleMapper.deleteRolePermissionsByRoleId(role.getId());
        //删除自己
        roleMapper.deleteById(role.getId());
        this.save(role);
    }

    /**
     * 新增角色
     * @param role
     */
    @Transactional
    @Override
    public void save(RoleRo role) {
        //保存角色表
        Role newRole = RoleRo.RoleRoToRole(role);
        roleMapper.save(newRole);
        Long roleId = newRole.getId();
        //保存角色和菜单
        roleMapper.saveRoleAndMenu(roleId,role.getMenus());
        //保存角色和权限
        roleMapper.saveRoleAndPermissions(roleId,role.getPermissions());
    }

    @Override
    public AjaxResult menuAndPermission(Long roleId) {
        //保存角色和菜单
        List<Menu> Menus = roleMapper.findRoleAndMenu(roleId);
        List<Long[]> collect = Menus.stream().map(menu -> {
//            List<Long> list = new ArrayList<>();
//            list.add(menu.getParentId());
//            list.add(menu.getId());
//            return list;
            Long[] longs =  new Long[2];
            longs[0] = menu.getParentId();
            longs[1] = menu.getId();
            return longs;
        }).collect(Collectors.toList());

        //保存角色和权限
        List<Long> permissions = roleMapper.findRoleAndPermissions(roleId);
        Map<String,Object> map = new HashMap<>();
        map.put("menus",collect);
        map.put("permissions",permissions);
        return AjaxResult.me().setResultObj(map);
    }
}
